#!/bin/bash
# HFT系统自动化部署脚本

# 初始化变量
LOG_FILE="deploy.log"
BACKUP_DIR="backup_$(date +%Y%m%d_%H%M%S)"
ENV_FILE=".env"

# 日志记录函数
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG_FILE
}

# 检查依赖及版本
check_dependencies() {
    log "检查系统依赖..."
    
    declare -A min_versions=(
        ["g++"]="9.0"
        ["cmake"]="3.15"
        ["make"]="4.0"
        ["git"]="2.0"
    )
    
    for cmd in "${!min_versions[@]}"; do
        if ! command -v $cmd &> /dev/null; then
            log "错误: 未找到 $cmd"
            exit 1
        fi
        
        version=$($cmd --version | head -n 1 | grep -oP '\d+\.\d+\.\d+' | head -1)
        if [ "$(printf '%s\n' "${min_versions[$cmd]}" "$version" | sort -V | head -n1)" != "${min_versions[$cmd]}" ]; then
            log "错误: $cmd 版本过低 (需要: ${min_versions[$cmd]}+, 当前: $version)"
            exit 1
        fi
    done
    
    log "所有依赖检查通过"
}

# 安装第三方库
install_third_party() {
    log "安装第三方库..."
    
    cd third_party || { log "无法进入third_party目录"; exit 1; }
    
    # 检查git子模块状态
    if [ ! -f .gitmodules ]; then
        log "错误: 缺少.gitmodules文件"
        exit 1
    fi
    
    git submodule update --init --recursive || { log "子模块更新失败"; exit 1; }
    
    # 构建googletest
    cd googletest || { log "无法进入googletest目录"; exit 1; }
    mkdir -p build && cd build || { log "无法创建build目录"; exit 1; }
    
    cmake .. || { log "cmake配置失败"; exit 1; }
    make -j$(nproc) || { log "编译失败"; exit 1; }
    sudo make install || { log "安装失败"; exit 1; }
    
    cd ../../..
    log "第三方库安装完成"
}

# 构建系统
build_system() {
    log "构建HFT系统..."
    
    # 创建备份
    mkdir -p $BACKUP_DIR
    [ -d build ] && mv build $BACKUP_DIR/build_$(date +%H%M%S)
    
    mkdir -p build && cd build || { log "无法创建build目录"; exit 1; }
    
    cmake .. -DCMAKE_BUILD_TYPE=Release || { log "cmake配置失败"; exit 1; }
    make -j$(nproc) || { log "编译失败"; exit 1; }
    
    cd ..
    log "系统构建完成"
}

# 配置环境
setup_config() {
    log "配置系统..."
    
    # 从环境变量文件加载配置
    if [ -f $ENV_FILE ]; then
        log "从$ENV_FILE加载环境变量"
        source $ENV_FILE
    else
        log "未找到$ENV_FILE文件，将提示输入配置"
    fi
    
    # 备份现有配置
    mkdir -p $BACKUP_DIR/config
    [ -f config/system_config.json ] && cp config/system_config.json $BACKUP_DIR/config/
    [ -f config/strategy_config.json ] && cp config/strategy_config.json $BACKUP_DIR/config/
    
    # 使用示例配置
    cp config/system_config.json.example config/system_config.json || { log "复制系统配置失败"; exit 1; }
    cp config/strategy_config.json.example config/strategy_config.json || { log "复制策略配置失败"; exit 1; }
    
    # 从环境变量或提示获取配置
    BROKER_ID=${BROKER_ID:-$(read -p "请输入CTP经纪商ID: " broker_id && echo $broker_id)}
    ACCOUNT=${ACCOUNT:-$(read -p "请输入CTP账户: " account && echo $account)}
    PASSWORD=${PASSWORD:-$(read -p "请输入CTP密码: " -s password && echo $password)}
    
    # 更新配置
    jq ".broker_id = \"$BROKER_ID\"" config/system_config.json > tmp.json && mv tmp.json config/system_config.json || { log "更新经纪商ID失败"; exit 1; }
    jq ".account = \"$ACCOUNT\" | .password = \"$PASSWORD\"" config/system_config.json > tmp.json && mv tmp.json config/system_config.json || { log "更新账户信息失败"; exit 1; }
    
    log "系统配置完成"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -h, --help     显示帮助信息"
    echo "  -e, --env      指定环境变量文件"
    echo "  -s, --skip     跳过依赖检查"
    echo "  -c, --clean    清理构建目录"
}

# 清理构建目录
clean_build() {
    log "清理构建目录..."
    rm -rf build
    log "清理完成"
}

# 主流程
main() {
    local skip_check=false
    local clean_build=false
    local env_file=""
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -e|--env)
                env_file="$2"
                shift
                ;;
            -s|--skip)
                skip_check=true
                ;;
            -c|--clean)
                clean_build=true
                ;;
            *)
                echo "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
        shift
    done
    
    # 设置环境变量文件
    if [ -n "$env_file" ]; then
        if [ -f "$env_file" ]; then
            ENV_FILE="$env_file"
        else
            log "警告: 指定的环境变量文件不存在: $env_file"
        fi
    fi
    
    # 清理构建目录
    if [ "$clean_build" = true ]; then
        clean_build
    fi
    
    # 检查依赖
    if [ "$skip_check" = false ]; then
        check_dependencies
    else
        log "跳过依赖检查"
    fi
    
    # 执行部署步骤
    install_third_party
    build_system
    setup_config
    
    log "HFT系统部署完成"
    log "运行程序: ./build/hft_system"
    log "详细日志请查看: $LOG_FILE"
}

main "$@"